'''
Created on 2010/03/24

@author: enu
'''

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from oauth2 import SignatureMethod_PLAINTEXT, SignatureMethod_HMAC_SHA1
from google.appengine.api import users
from oauth.serviceprovider import ServiceProvider
from oauth.signature import SignatureMethodStore

debug = True

def initialize():
  SignatureMethodStore.addSignatureMethod(SignatureMethod_PLAINTEXT)
  SignatureMethodStore.addSignatureMethod(SignatureMethod_HMAC_SHA1)

class OAuthInitiatePage(webapp.RequestHandler):
  def __init__(self):
    self._server = ServiceProvider()
  def get(self):
    self._server.requestTemporaryTokenCredentials(self.request, self.response)
  def post(self):
    self.get()

class OAuthAuthorizePage(webapp.RequestHandler):
  def __init__(self):
    self._server = ServiceProvider()
  def get(self):
    user = users.get_current_user()
    if not user:
      users.create_login_url(self.request.url) 
    self._server.authorizeAcess(self.request, self.response, user)
    pass
  def post(self):
    self.get()

class OAuthTokenPage(webapp.RequestHandler):
  def __init__(self):
    self._server = ServiceProvider()
  def get(self):
    self._server.issueAuthorizedTokenCredentials(self.request, self.response)
  def post(self):
    self.get()

routes = [
  ('/oauth/initiate',   OAuthInitiatePage),
  ('/oauth/authorize',  OAuthAuthorizePage),
  ('/oauth/token',      OAuthTokenPage)
       ]
application = webapp.WSGIApplication(routes, debug=debug)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()